﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using Telerik.Framework.Search;
using Telerik.Events;
using SelArom.Net.Sitefinity.API.Events.Data;

namespace SelArom.Net.Sitefinity.IndexProviders.Events
{
    /// <summary>
    /// Indexes items from the default provider (only) of the Events Module
    /// </summary>
    public class EventIndexProvider : IIndexingServiceClient
    {
        /// <summary>
        /// Defines the name of the provider. This name is used to mange providers within Indexing Service.
        /// </summary>
        public string Name
        {
            get
            {
                return "EventsIndexProvider";
            }
        }

        /// <summary>
        /// Provides detailed description of the client
        /// </summary>
        public string Description
        {
            get
            {
                return "Provides indexing for events.";
            }
        }

        /// <summary>
        /// Meta fields for this provider
        /// </summary>
        protected string[] MetaFields
        {
            get
            {
                return new[]{
					"Title",
                    "Category"
				};
            }
        }

        public IIndexerInfo[] GetContentToIndex()
        {
            var list = new List<IIndexerInfo>();

			// retrieve events
            foreach (IEvent ev in new EventsManager(EventsManager.DefaultContentProvider).GetEvents())
            {
				// skip past events
				if (ev.End < DateTime.Now) continue;

				// init meta fields
                var metaFields = new Hashtable();            
                foreach (var key in MetaFields)
                {
                    metaFields.Add(key, "");
                }

                metaFields["Title"] = ev.EventTitle;
            	metaFields["Category"] = ev.ContentItem.GetMetaData("Category");

				// ensure url appkey is present, create url and index item
				var evUrl = ConfigurationManager.AppSettings[EventsManager.DefaultContentProvider + "Url"];
				if (string.IsNullOrEmpty(evUrl)) break;
				var url = string.Concat(evUrl, ev.ContentItem.UrlWithExtension.ToLower());
                list.Add(
                    new EventIndexerInfo(
                    url,
                    metaFields,
                    ev.ContentItem.Content.ToString(),
					new Guid()));
            }

            return list.ToArray();
        }

        public string[] GetUrlsToIndex()
        {
            return new string[0];
        }

        public event EventHandler<IndexEventArgs> Index;

        public void Initialize(IDictionary<string, string> settings)
        {
        }
    }
}